/*********************************************************************************
 *      Copyright:  (C) 2023 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  sht20.c
 *    Description:  This file for sht20.c.
 *                 
 *        Version:  1.0.0(2023年07月11日)
 *         Author:  Ling Yun <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "2023年07月11日 15时24分12秒"
 *                 
 ********************************************************************************/

#include "sht20.h"

static inline void msleep(unsigned long ms)
{
	struct timespec cSleep;
	unsigned long ulTmp;

	cSleep.tv_sec = ms / 1000;
	if(cSleep.tv_sec == 0)
	{
		ulTmp = ms * 10000;
		cSleep.tv_nsec = ulTmp * 100;
	}
	else{
		cSleep.tv_nsec = 0;
	}

	nanosleep(&cSleep,0);
}

int sht2x_softreset( int fd )
{
	uint8_t		buf[4];

	if(fd < 0)
	{
		printf("%s line [%d] %s() get invalid input arguments\n",__FILE__,__LINE__,__func__);
		return -1;
	}

	memset(buf,0,sizeof(buf));

	buf[0] = SOFTRESET;
	write(fd,buf,1);

	msleep(50);
	return 0;
}

int sht2x_init(void)
{
	int 	fd;

	if((fd = open(SHT20_PATH,O_RDWR)) < 0 )
	{
		printf("fail to open sht20\n");
		return -1;
	}

	ioctl(fd,I2C_TENBIT,0);
	ioctl(fd,I2C_SLAVE,0X40);

	if( sht2x_softreset(fd) < 0 )
	{
		printf("fail to softreset sht20\n");
		return -2;
	}

	return fd;
}


int sht2x_get_temp_humidity(int fd, unsigned char *buf_temp, unsigned char *buf_rh, float *temp, float *rh)
{
	uint8_t	buf[4];

	if(fd < 0 || !temp || !rh)
	{
		printf("%s line [%d] %s() get invalid input arguments\n",__FILE__,__LINE__,__func__);
		return -1;
	}

	memset(buf,0,sizeof(buf));
	buf[0]=TRIGGER_TEMPERATURE_NO_HOLD;
	write(fd,buf, 1);

	msleep(85);

	memset(buf,0,sizeof(buf));
	read(fd,buf,3);
	*buf_temp = *buf;
	*(buf_temp+1) = *(buf+1);
	*(buf_temp+2) = *(buf+2);
	*temp = 175.72 * (((((int) buf[0]) << 8) + buf[1]) / 65536.0) - 46.85;

	memset(buf,0,sizeof(buf));
	buf[0] = TRIGGER_HUMIDITY_NO_HOLD;
	write(fd,buf,1);

	msleep(29);
	memset(buf,0,sizeof(buf));

	read(fd,buf,3);
	*buf_rh = *buf;
	*(buf_rh+1) = *(buf+1);
	*(buf_rh+2) = *(buf+2);
	*rh = 125 *(((((int) buf[0]) << 8) + buf[1]) / 65536.0) - 6;

	return 0;
}
